import { useUIStore } from "@/store/ui"
import { equ } from "../../package-env"

/**
 * 监测是否是微信浏览器内核
 * @returns {boolean}
 */
export function isWechat() {
  const ua = navigator.userAgent.toLowerCase()
  return ua.indexOf('micromessenger') > -1
}

/**
 * 监测是否是安卓 Webview
 * @returns {boolean}
 */
export function isAndroid() {
  const ua = navigator.userAgent.toLowerCase()
  return ua.indexOf('android') > -1
}

/**
 * 监测是否是IOS Webview
 * @returns {boolean}
 */
export function isIos() {
  return !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
}

/**
 * 检测是否是移动端
 * @returns {boolean}
 */
export function isApp() {
  return (isIos() || isAndroid())
}

/**
 * JS API `getUserMedia` 兼容
 * @returns
 */
export function getUserMediaApi() {
  const navigatorNative = navigator as LooseObject
  const mediaDevices = navigatorNative.mediaDevices
  const getUserMedia = mediaDevices ? mediaDevices.getUserMedia : undefined
  if (mediaDevices && getUserMedia) {
    navigatorNative.getUserMedia = (ops, success, error) => {
      return mediaDevices.getUserMedia(ops).then(success).catch(error)
    }
  } else if (!getUserMedia) {
    navigatorNative.getUserMedia =
      navigatorNative.getUserMedia ||
      navigatorNative.webkitGetUserMedia ||
      navigatorNative.mozGetUserMedia ||
      navigatorNative.msGetUserMedia
  }
  return navigatorNative.getUserMedia()
}

export function getMediaStream(): Promise<MediaStream> {
  const constrains = { video: false, audio: true }
  const navigatorGetUserMedia =
    navigator.getUserMedia ||
    navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia ||
    navigator.msGetUserMedia
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    return navigator.mediaDevices.getUserMedia(constrains)
  } else if (navigatorGetUserMedia) {
    return navigatorGetUserMedia(constrains)
  } else if (
    navigator.userAgent.toLowerCase().match(/chrome/) &&
    location.origin.indexOf('https://') < 0
  ) {
    return Promise.reject(
      new Error(
        'chrome下获取浏览器媒体功能，因为安全性问题，需要在localhost或127.0.0.1或https下才能获取权限'
      )
    )
  } else {
    return Promise.reject(new Error('无法获取浏览器媒体功能，请升级浏览器或使用chrome'))
  }
}

/**
 * 微信内禁止下拉网页
 * @export
 */
export function noPullPage() {
  if (isWechat()) {
    document.body.style.overflow = 'hidden'
  }
}


/**
 * 判断ios系统版本
 * @export
 */
export function iosVersion() {
  const str = navigator.userAgent.toLowerCase();
  const ver = str.match(/cpu iphone os (.*?) like mac os/);

  if (ver && ver[1]) {
    const result: LooseObject = ver[1].split('_')
    // ios15不显示
    return result[0] !== 15
  }
  return false
}

/**
 * 判断是否支持webp图片
 * @export
 */
export function checkWebpFeature(feature, callback) {
  const kTestImages = {
    lossy: "UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",
    lossless: "UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==",
    alpha: "UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==",
    animation: "UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA"
  }
  const img = new Image()
  img.onload = function () {
    const result = (img.width > 0) && (img.height > 0)
    callback(feature, result)
  };
  img.onerror = function () {
    callback(feature, false)
  }
  img.src = "data:image/webp;base64," + kTestImages[feature]
}

const params = useUrlSearchParams()
/**
 * 图片资源转换
 * @export
 */
export function transformImage(url: string, isApng?: boolean) {
  if (equ === 'pc') return url;
  const ui = useUIStore()
  const currentUrl = 'https://fivdfiles.xmov.ai'
  const newUrl = 'https://cdn-public-ali.xmov.ai/xmov-xforce'
  let result = url

  if (params?.img_type === 'self') return result

  result = url.replace(currentUrl, newUrl)

  if (isApng) return result

  if (ui.isSupportWebp) {
    return result + `?x-oss-process=image/format,webp`
  } else {
    return result
  }
}
